package com.aba.hos.doc.gui;

import com.aba.hos.admin.Admin;
import com.aba.hos.admin.AdminLoginExampleWindow;
import com.aba.hos.dao.AdminDao;
import com.aba.hos.dao.PatDao;
import com.aba.hos.dao.impl.AdminDaoImpl;
import com.aba.hos.dao.impl.PatDaoImpl;
import com.aba.hos.doc.entity.Doctor;
import com.aba.hos.doc.entity.Patient;
import com.aba.hos.doc.entity.Ward;
import com.aba.hos.doc.service.HospitalService;
import com.aba.hos.totality.LoginWindow;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * 医院管理系统图形界面主类
 */
@SuppressWarnings({"unused", "serial"})
public class HospitalManagementGUI extends JFrame {
    private final HospitalService hospitalService;
    private JTabbedPane tabbedPane;
    private AdminDao adminDao = new AdminDaoImpl();
    private PatDao patDao = new PatDaoImpl();

    // 新增：病人表格模型成员变量
    private DefaultTableModel patientTableModel;
    private String currentUserName; // 当前用户姓名（用于查询对应病人）

    public HospitalManagementGUI(String name, String role) throws SQLException {
        currentUserName = name; // 初始化当前用户名
        hospitalService = new HospitalService();
        initializeUI(name, role);
        loadSampleData();
    }

    private void initializeUI(String name, String role) throws SQLException {
        setTitle("医院病人管理系统");
        setSize(1000, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        add(mainPanel);

        tabbedPane = new JTabbedPane();
        mainPanel.add(tabbedPane, BorderLayout.CENTER);

        tabbedPane.addTab("概览", createOverviewPanel(name,role));
        tabbedPane.addTab("病人管理", createPatientPanel(role,name)); // 传递当前用户名
        if (role.equals("管理员")) {
            tabbedPane.addTab("医生管理", createDoctorPanel("管理员"));
        }
        tabbedPane.addTab("病房管理", createWardPanel());
    }

    private JPanel createOverviewPanel(String name, String role) throws SQLException {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建顶部统计信息面板
        JPanel statsPanel = new JPanel(new GridLayout(2, 3, 10, 10));
        statsPanel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(statsPanel, BorderLayout.NORTH);

        // 同质化床位数量（原逻辑）
        int total = 20 + 10 + 5;

        // 添加统计卡片（原逻辑）
        statsPanel.add(createStatCard("总病人数", () -> String.valueOf(patDao.queryPatTotal().size())));
        statsPanel.add(createStatCard("当前住院病人", () -> String.valueOf(patDao.queryPat().size())));
        statsPanel.add(createStatCard("医生总数", () -> String.valueOf(adminDao.queryAdminRole("医生").size())));
        statsPanel.add(createStatCard("病房总数", () -> String.valueOf(hospitalService.getTotalWards())));
        statsPanel.add(createStatCard("可用床位", () -> String.valueOf(total - patDao.queryPat().size())));

        JPanel buttonPanel = new JPanel();
        panel.add(buttonPanel, BorderLayout.SOUTH);
        String labelText = "退出登录";
        if(role.equals("管理员")){
            labelText = "返回主页面";
        }
        // 添加返回按钮（所有角色均显示，点击事件根据角色区分）
        JButton returnButton = new JButton(labelText);
        buttonPanel.add(returnButton);
        System.out.println("角色："+role);
        returnButton.addActionListener(e -> {
            if (role.equals("管理员")) {
                // 管理员返回逻辑：示例为跳转到登录页面（根据实际需求修改）
                new AdminLoginExampleWindow().openMainPage(name, "管理员");
                dispose(); // 关闭当前窗口
            } else {
                // 普通用户（如医生）返回逻辑：示例为回到登录页面
                new LoginWindow();
                dispose(); // 关闭当前窗口
            }
        });

        JPanel activitiesPanel = new JPanel(new BorderLayout());
        activitiesPanel.setBorder(BorderFactory.createTitledBorder("最近活动"));
        panel.add(activitiesPanel, BorderLayout.CENTER);

        JTextArea activitiesArea = new JTextArea("欢迎使用医院病人管理系统！\n\n请使用顶部标签页导航到各个功能模块。");
        activitiesArea.setEditable(false);
        activitiesArea.setLineWrap(true);
        activitiesArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(activitiesArea);
        activitiesPanel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createStatCard(String title, StatValueProvider valueProvider) throws SQLException {
        JPanel card = new JPanel(new BorderLayout());
        card.setBackground(Color.WHITE);
        card.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Arial", Font.PLAIN, 14));
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        titleLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
        card.add(titleLabel, BorderLayout.NORTH);

        JLabel valueLabel = new JLabel(valueProvider.getValue());
        valueLabel.setFont(new Font("Arial", Font.BOLD, 24));
        valueLabel.setHorizontalAlignment(JLabel.CENTER);
        valueLabel.setBorder(new EmptyBorder(10, 5, 10, 5));
        card.add(valueLabel, BorderLayout.CENTER);

        // 添加定时器，定期更新统计值
        Timer timer = new Timer(1000, e -> {
            try {
                valueLabel.setText(valueProvider.getValue());
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        timer.start();

        return card;
    }

    private JPanel createPatientPanel(String role,String name) throws SQLException {

        java.util.List<Patient> patientList = patDao.queryPatByNameAllList();
        if(role.equals("医生")){
            patientList = patDao.queryPatByNameList(name);
        }

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建病人表格并保存模型到成员变量
        String[] columnNames = {"ID", "姓名", "年龄", "性别", "诊断", "入院日期", "主治医生", "病房"};
        patientTableModel = new DefaultTableModel(columnNames, 0);
        JTable patientTable = new JTable(patientTableModel);
        JScrollPane tableScrollPane = new JScrollPane(patientTable);
        panel.add(tableScrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        panel.add(buttonPanel, BorderLayout.SOUTH);


        JButton addButton = new JButton("添加病人");
        JButton editButton = new JButton("修改症状");
        if(role.equals("管理员")) {
            JButton assignButton = new JButton("分配医生");
            buttonPanel.add(assignButton);
            if(role.equals("管理员")) {
                assignButton.addActionListener(e -> {
                    try {
                        int selectedRow = patientTable.getSelectedRow();
                        if (selectedRow == -1) {
                            JOptionPane.showMessageDialog(null, "请选择需要分配医生的病人", "提示", JOptionPane.WARNING_MESSAGE);
                            return;
                        }
                        int patientId = Integer.parseInt(patientTable.getValueAt(selectedRow, 0).toString());
                        showSelectDoctorDialog(patientId, role); // 新增选择医生对话框
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, "操作失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                });
            }else{
                //分配给医生自己
                assignButton.addActionListener(e -> {
                    int selectedRow = patientTable.getSelectedRow();
                    int patientId = Integer.parseInt(patientTable.getValueAt(selectedRow, 0).toString());
                    try {
                        patDao.updatePatDoc(name, String.valueOf(patientId));
                        JOptionPane.showMessageDialog(this, "病人分配给自己！");
                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                });
            }
        }
        JButton dischargeButton = new JButton("办理出院");
        JButton refreshButton = new JButton("刷新");



        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(dischargeButton);
        buttonPanel.add(refreshButton);
        addButton.addActionListener(e -> showAddPatientDialog(name,role));

        editButton.addActionListener(e -> {
            try {
                showEditPatientDialog(patientTable,role);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        dischargeButton.addActionListener(e -> {
            try {
                dischargeSelectedPatient(patientTable,role);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });
        refreshButton.addActionListener(e -> refreshPatientTable(patientTableModel, role, name)); // 使用成员模型

        fillTableData(patientTableModel, patientList); // 使用成员模型填充数据
        return panel;
    }

    // 填充表格数据的方法
    private void fillTableData(DefaultTableModel tableModel, java.util.List<Patient> patientList) {
        // 清空现有数据
        tableModel.setRowCount(0);

        // 将 patientList 中的数据逐行添加到表格
        for (Patient patient : patientList) {
            tableModel.addRow(new Object[]{
                    patient.getId(),
                    patient.getName(),           // 姓名
                    patient.getAge(),            // 年龄
                    patient.getGender(),
                    patient.getDiagnosis(),      // 诊断
                    patient.getAdmissionDate(),  // 入院日期
                    patient.getDocId(),     // 主治医生
                    patient.getBedNumber(),      // 诊断
            });
        }
    }

    // 刷新表格的方法（修改为接收 name 参数）
    private void refreshPatientTable(DefaultTableModel tableModel, String role,String name) {
        try {
            java.util.List<Patient> patientList = patDao.queryPatByNameAllList();
            if(role.equals("医生")){
                patientList =new ArrayList<Patient>();
                patientList = patDao.queryPatByNameList(name);
            }
            fillTableData(tableModel, patientList);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "刷新表格失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showAddPatientDialog(String docName,String role) {

        JDialog dialog = new JDialog(this, "添加病人", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel formPanel = new JPanel(new GridLayout(6, 2, 10, 10));
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JTextField nameField = new JTextField();
        JTextField ageField = new JTextField();
        JTextField diagnosisField = new JTextField();

        String[] genders = {"男", "女"};
        JComboBox<String> genderComboBox = new JComboBox<>(genders);

        String[] wardTypes = {"普通病房", "单人病房", "VIP病房"};
        JComboBox<String> wardComboBox = new JComboBox<>(wardTypes);

        formPanel.add(new JLabel("姓名:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("年龄:"));
        formPanel.add(ageField);
        formPanel.add(new JLabel("性别:"));
        formPanel.add(genderComboBox); // 添加下拉框而非文本框
        formPanel.add(new JLabel("诊断:"));
        formPanel.add(diagnosisField);
        formPanel.add(new JLabel("病房类型:"));
        formPanel.add(wardComboBox); // 添加下拉框而非文本框

        dialog.add(formPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String name = nameField.getText();
                int age = Integer.parseInt(ageField.getText());
                String gender = (String) genderComboBox.getSelectedItem(); // 获取选中的性别
                String diagnosis = diagnosisField.getText();
                String bedNumber = (String) wardComboBox.getSelectedItem(); // 获取选中的病房类型

                // 创建病人对象，传入病房类型
                Patient patient = new Patient(name, age, gender, diagnosis, bedNumber, docName, null);
                patDao.addPat(patient);

                JOptionPane.showMessageDialog(this, "病人添加成功！");
                dialog.dispose();

                // 刷新表格
                if (patientTableModel != null) {
                    refreshPatientTable(patientTableModel, role, currentUserName);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "年龄必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "添加病人失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void showEditPatientDialog(JTable table,String role) throws SQLException {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个病人！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int patientId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Patient patient = patDao.queryPatById(patientId);

        if (patient == null) {
            JOptionPane.showMessageDialog(this, "找不到该病人！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "修改症状", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JTextField diagnosisField = new JTextField(patient.getDiagnosis());
        formPanel.add(new JLabel("诊断:"));
        formPanel.add(diagnosisField);

        dialog.add(formPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                patient.setDiagnosis(diagnosisField.getText());
                patDao.updatePatWordDiagnosis(patient); // 更新数据库
                JOptionPane.showMessageDialog(this, "病人信息更新成功！");
                dialog.dispose();

                // 刷新病人表格（使用当前用户名查询）
                if (patientTableModel != null) {
                    refreshPatientTable(patientTableModel, role,currentUserName);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "年龄必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "更新病人信息失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());
        dialog.setVisible(true);
    }

    private void dischargeSelectedPatient(JTable table,String role) throws SQLException {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个病人！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int patientId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Patient patient = patDao.queryPatById(patientId);

        if (patient == null) {
            JOptionPane.showMessageDialog(this, "找不到该病人！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (patient.isDischarged()) {
            JOptionPane.showMessageDialog(this, "该病人已出院！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要办理 " + patient.getName() + " 的出院手续吗？",
                "确认出院",
                JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            patDao.updatePatStatus(String.valueOf(patientId));
            JOptionPane.showMessageDialog(this, "病人出院手续已办理！");
            // 刷新病人表格（使用当前用户名查询）
            if (patientTableModel != null) {
                refreshPatientTable(patientTableModel, role,currentUserName);
            }
        }
    }

    private void refreshPatientTable(DefaultTableModel model) {
        model.setRowCount(0);
        java.util.List<Patient> patients = hospitalService.getAllPatients();
        for (Patient patient : patients) {
            String doctorName = patient.getAttendingDoctor() != null ?
                    patient.getAttendingDoctor().getName() : "未分配";
            String wardNumber = patient.getWard() != null ?
                    String.valueOf(patient.getWard().getWardNumber()) : "未分配";
            String status = patient.isDischarged() ? "已出院" : "住院中";

            model.addRow(new Object[]{
                patient.getId(),
                patient.getName(),
                patient.getAge(),
                patient.getGender(),
                patient.getDiagnosis(),
                patient.getAdmissionDate(),
                doctorName,
                wardNumber,
                status
            });
        }
    }

    private JPanel createDoctorPanel(String role) throws SQLException {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建医生表格
        String[] columnNames = {"ID", "姓名", "专科", "负责病人数"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable doctorTable = new JTable(tableModel);
        JScrollPane tableScrollPane = new JScrollPane(doctorTable);
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        panel.add(buttonPanel, BorderLayout.SOUTH);

        if(role.equals("管理员") || role.equals("超级管理员")) {
            JButton addButton = new JButton("添加医生");
            buttonPanel.add(addButton);
            addButton.addActionListener(e -> showAddDoctorDialog(role));

        JButton editButton = new JButton("编辑医生");
        buttonPanel.add(editButton);
        editButton.addActionListener(e -> showEditDoctorDialog(doctorTable));
        }

        JButton refreshButton = new JButton("刷新");
        buttonPanel.add(refreshButton);
        refreshButton.addActionListener(e -> {
            try {
                refreshDoctorTable(tableModel);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });

        // 初始化表格数据
        refreshDoctorTable(tableModel);

        return panel;
    }

    private void showAddDoctorDialog(String role) {
        JDialog dialog = new JDialog(this, "添加医生", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 使用垂直 BoxLayout 布局
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setBorder(new EmptyBorder(15, 15, 15, 15));

        // 创建并保存对输入框的引用
        JTextField usernameField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        JTextField nameField = new JTextField();
        JTextField specialtyField = new JTextField();
        JTextField contactInfoField = new JTextField();
        JTextField positionField = new JTextField();

        // 添加所有字段
        addFormField(formPanel, "账号:", usernameField);
        addFormField(formPanel, "密码:", passwordField);
        addFormField(formPanel, "姓名:", nameField);
        addFormField(formPanel, "专科:", specialtyField);
        addFormField(formPanel, "电话:", contactInfoField);

        dialog.add(formPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
                // 直接使用保存的引用获取输入值，避免类型转换问题
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                String name = nameField.getText();
                String specialty = specialtyField.getText();
                String contactInfo = contactInfoField.getText();
                String position = positionField.getText();

                // 创建Admin对象
                Admin admin = new Admin(username,username, password, name, contactInfo, "医生",specialty);
            try {
                adminDao.addAdmin(admin);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }

            JOptionPane.showMessageDialog(this, "医生添加成功！");
                dialog.dispose();
    //                refreshAllTables();
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    // 辅助方法：创建一个包含标签和输入框的面板，并添加到父面板
    private void addFormField(JPanel parent, String labelText, JComponent field) {
        JPanel panel = new JPanel(new BorderLayout(5, 5)); // 标签和输入框之间的间距
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 35)); // 设置最大高度，保持一致
        panel.setAlignmentX(Component.LEFT_ALIGNMENT); // 左对齐

        JLabel label = new JLabel(labelText);
        label.setPreferredSize(new Dimension(80, 25)); // 设置标签宽度，保持一致

        panel.add(label, BorderLayout.WEST);
        panel.add(field, BorderLayout.CENTER);

        parent.add(panel);
        parent.add(Box.createVerticalStrut(10)); // 添加垂直间距
    }


    private void showEditDoctorDialog(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个医生！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int doctorId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Doctor doctor = hospitalService.findDoctorById(doctorId);

        if (doctor == null) {
            JOptionPane.showMessageDialog(this, "找不到该医生！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "编辑医生", true);
        dialog.setSize(350, 200);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel formPanel = new JPanel(new GridLayout(2, 2, 10, 10));
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JTextField nameField = new JTextField(doctor.getName());
        JTextField specialtyField = new JTextField(doctor.getSpecialty());

        formPanel.add(new JLabel("姓名:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("专科:"));
        formPanel.add(specialtyField);

        dialog.add(formPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                doctor.setName(nameField.getText());
                doctor.setSpecialty(specialtyField.getText());
                int patientId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());

                adminDao.updateAdminDoc(String.valueOf(patientId), nameField.getText(), specialtyField.getText());

                JOptionPane.showMessageDialog(this, "医生信息更新成功！");
                dialog.dispose();
    //                refreshAllTables();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "更新医生信息失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void showAssignPatientDialog(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个医生！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int doctorId = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Doctor doctor = hospitalService.findDoctorById(doctorId);

        if (doctor == null) {
            JOptionPane.showMessageDialog(this, "找不到该医生！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "分配病人给 " + doctor.getName(), true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 创建可分配病人列表
        String[] columnNames = {"ID", "姓名", "诊断", "状态"};
        DefaultTableModel patientModel = new DefaultTableModel(columnNames, 0);
        JTable patientTable = new JTable(patientModel);

        // 填充可分配病人（未出院且未分配给该医生的病人）
        java.util.List<Patient> allPatients = hospitalService.getActivePatients();
        for (Patient patient : allPatients) {
            if (patient.getAttendingDoctor() == null ||
                patient.getAttendingDoctor().getId() != doctorId) {
                patientModel.addRow(new Object[]{
                    patient.getId(),
                    patient.getName(),
                    patient.getDiagnosis(),
                    patient.getAttendingDoctor() == null ? "未分配" : "已分配"
                });
            }
        }

        JScrollPane patientScrollPane = new JScrollPane(patientTable);
        dialog.add(patientScrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton assignButton = new JButton("分配");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(assignButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        assignButton.addActionListener(e -> {
            int selectedPatientRow = patientTable.getSelectedRow();
            if (selectedPatientRow == -1) {
                JOptionPane.showMessageDialog(dialog, "请先选择一个病人！", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            int patientId = Integer.parseInt(patientTable.getValueAt(selectedPatientRow, 0).toString());
//            Patient patient = hospitalService.findPatientById(patientId);
            Patient patient = null;

            if (patient == null) {
                JOptionPane.showMessageDialog(dialog, "找不到该病人！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            hospitalService.assignDoctorToPatient(doctorId, patientId);
            JOptionPane.showMessageDialog(dialog, "病人已成功分配给医生！");
            dialog.dispose();
//                refreshAllTables();
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void refreshDoctorTable(DefaultTableModel model) throws SQLException {
        model.setRowCount(0);
        java.util.List<Admin> doctors = adminDao.queryAdminRole("医生");
        for (Admin doctor : doctors) {
            java.util.List<Patient> patList = patDao.queryPatByNameList(doctor.getName());

            model.addRow(new Object[]{
                doctor.getId(),
                doctor.getName(),
                doctor.getPosition(),
                patList.size()
            });
        }
    }

    private JPanel createWardPanel() throws SQLException {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建病房表格
        String[] columnNames = {"编号", "类型", "容量", "已占用", "可用床位"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable wardTable = new JTable(tableModel);
        JScrollPane tableScrollPane = new JScrollPane(wardTable);
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        panel.add(buttonPanel, BorderLayout.SOUTH);


        JButton refreshButton = new JButton("刷新");


        buttonPanel.add(refreshButton);

        refreshButton.addActionListener(e -> {
            try {
                refreshWardTable(tableModel);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        });

        // 初始化表格数据
        Ward ward1 = new Ward("普通病房", 20);
        Ward ward2 = new Ward("高级病房", 10);
        Ward ward3 = new Ward("ICU", 5);
        hospitalService.addWard(ward1);
        hospitalService.addWard(ward2);
        hospitalService.addWard(ward3);
        refreshWardTable(tableModel);

        return panel;
    }

    private void showAddWardDialog() {
        JDialog dialog = new JDialog(this, "添加病房", true);
        dialog.setSize(350, 200);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel formPanel = new JPanel(new GridLayout(2, 2, 10, 10));
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        JTextField typeField = new JTextField();
        JTextField capacityField = new JTextField();

        formPanel.add(new JLabel("病房类型:"));
        formPanel.add(typeField);
        formPanel.add(new JLabel("床位容量:"));
        formPanel.add(capacityField);

        dialog.add(formPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String type = typeField.getText();
                int capacity = Integer.parseInt(capacityField.getText());

                if (capacity <= 0) {
                    JOptionPane.showMessageDialog(this, "床位容量必须大于0！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                Ward ward = new Ward(type, capacity);
                hospitalService.addWard(ward);

                JOptionPane.showMessageDialog(this, "病房添加成功！");
                dialog.dispose();
    //                refreshAllTables();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "床位容量必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "添加病房失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void showAssignWardDialog(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个病房！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int wardNumber = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Ward ward = hospitalService.findWardByNumber(wardNumber);

        if (ward == null) {
            JOptionPane.showMessageDialog(this, "找不到该病房！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (ward.getAvailableBeds() <= 0) {
            JOptionPane.showMessageDialog(this, "该病房已满！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "分配病人到病房 " + wardNumber, true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 创建可分配病人列表
        String[] columnNames = {"ID", "姓名", "诊断", "当前病房"};
        DefaultTableModel patientModel = new DefaultTableModel(columnNames, 0);
        JTable patientTable = new JTable(patientModel);

        // 填充可分配病人（未出院且未分配到该病房的病人）
        java.util.List<Patient> allPatients = hospitalService.getActivePatients();
        for (Patient patient : allPatients) {
            patientModel.addRow(new Object[]{
                patient.getId(),
                patient.getName(),
                patient.getDiagnosis(),
                patient.getWard() == null ? "未分配" : patient.getWard().getWardNumber()
            });
        }

        JScrollPane patientScrollPane = new JScrollPane(patientTable);
        dialog.add(patientScrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton assignButton = new JButton("分配");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(assignButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        assignButton.addActionListener(e -> {
            int selectedPatientRow = patientTable.getSelectedRow();
            if (selectedPatientRow == -1) {
                JOptionPane.showMessageDialog(dialog, "请先选择一个病人！", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            int patientId = Integer.parseInt(patientTable.getValueAt(selectedPatientRow, 0).toString());
//            Patient patient = hospitalService.findPatientById(patientId);
            Patient patient = null;

            if (patient == null) {
                JOptionPane.showMessageDialog(dialog, "找不到该病人！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (hospitalService.assignPatientToWard(patientId, wardNumber)) {
                JOptionPane.showMessageDialog(dialog, "病人已成功分配到病房！");
                dialog.dispose();
    //                refreshAllTables();
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void showViewWardDialog(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一个病房！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int wardNumber = Integer.parseInt(table.getValueAt(selectedRow, 0).toString());
        Ward ward = hospitalService.findWardByNumber(wardNumber);

        if (ward == null) {
            JOptionPane.showMessageDialog(this, "找不到该病房！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "病房 " + wardNumber + " 病人列表", true);
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 创建病房病人列表
        String[] columnNames = {"ID", "姓名", "年龄", "性别", "诊断", "主治医生"};
        DefaultTableModel patientModel = new DefaultTableModel(columnNames, 0);
        JTable patientTable = new JTable(patientModel);

        // 填充病房病人
        for (Patient patient : ward.getPatients()) {
            String doctorName = patient.getAttendingDoctor() != null ?
                    patient.getAttendingDoctor().getName() : "未分配";

            patientModel.addRow(new Object[]{
                patient.getId(),
                patient.getName(),
                patient.getAge(),
                patient.getGender(),
                patient.getDiagnosis(),
                doctorName
            });
        }

        JScrollPane patientScrollPane = new JScrollPane(patientTable);
        dialog.add(patientScrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton closeButton = new JButton("关闭");
        buttonPanel.add(closeButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        closeButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void refreshWardTable(DefaultTableModel model) throws SQLException {
        model.setRowCount(0);

        java.util.List<Ward> wards = hospitalService.getAllWards();
        for (Ward ward : wards) {

            model.addRow(new Object[]{
                ward.getWardNumber(),
                ward.getType(),
                ward.getCapacity(),
                patDao.queryRoomNumber(ward.getType()).size(),
                (ward.getCapacity() - patDao.queryRoomNumber(ward.getType()).size())
            });
        }
    }

    private void refreshTablesInPanel(JPanel panel) throws SQLException {
        Component[] components = panel.getComponents();
        for (Component component : components) {
            if (component instanceof JScrollPane) {
                JScrollPane scrollPane = (JScrollPane) component;
                JViewport viewport = scrollPane.getViewport();
                if (viewport.getView() instanceof JTable) {
                    JTable table = (JTable) viewport.getView();
                    DefaultTableModel model = (DefaultTableModel) table.getModel();

                    // 根据表格列名判断刷新哪种表格
                    if (model.getColumnCount() > 0) {
                        String firstColumnName = model.getColumnName(0);
                        if ("ID".equals(firstColumnName) && "姓名".equals(model.getColumnName(1))) {
                            refreshPatientTable(model);
                        } else if ("ID".equals(firstColumnName) && "专科".equals(model.getColumnName(2))) {
                            refreshDoctorTable(model);
                        } else if ("编号".equals(firstColumnName)) {
                            refreshWardTable(model);
                        }
                    }
                }
            } else if (component instanceof JPanel) {
                refreshTablesInPanel((JPanel) component);
            } else if (component instanceof JSplitPane) {
                JSplitPane splitPane = (JSplitPane) component;
                refreshTablesInPanel((JPanel) splitPane.getTopComponent());
                refreshTablesInPanel((JPanel) splitPane.getBottomComponent());
            }
        }
    }
    private void loadSampleData() throws SQLException {

        java.util.List<Admin> adminList = adminDao.queryAdminRole("医生");
        java.util.List<Patient> patList = patDao.queryPat();
        for (Patient p : patList){
            hospitalService.addPatient(p);
        }
        // 添加医生
        for (Admin a :  adminList){
            Doctor doctor = new Doctor(a.getId(),a.getName(),a.getPosition());
            hospitalService.addDoctor(doctor);
            long count = patList.stream()
                    .filter(patient -> patient.getId() == a.getId())
                    .count();
            hospitalService.assignDoctorToPatient(a.getId(), a.getId());
        }


////        // 添加病房
////        Ward ward1 = new Ward("普通病房", 20);
////        Ward ward2 = new Ward("高级病房", 10);
////        Ward ward3 = new Ward("ICU", 5);
////        hospitalService.addWard(ward1);
////        hospitalService.addWard(ward2);
////        hospitalService.addWard(ward3);
//
//        for (Patient p :patList){
//            hospitalService.assignPatientToWard(p.getId(), ward1.getWardNumber());
//        }
        // 分配病房
    }

    private void showSelectDoctorDialog(int patientId, String role) throws SQLException {
        JDialog dialog = new JDialog(this, "选择主治医生", true);
        dialog.setSize(300, 200);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 获取所有医生列表
        java.util.List<Admin> doctors = adminDao.queryAdminRole("医生");

        // 创建下拉框并填充医生数据
        JComboBox<Admin> doctorComboBox = new JComboBox<>();
        for (Admin doctor : doctors) {
            doctorComboBox.addItem(doctor);
        }
        doctorComboBox.setRenderer(new DoctorListRenderer()); // 设置自定义渲染器

        JPanel formPanel = new JPanel(new BorderLayout(10, 10));
        formPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
        formPanel.add(new JLabel("选择主治医生："), BorderLayout.WEST);
        formPanel.add(doctorComboBox, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                Admin selectedDoctor = (Admin) doctorComboBox.getSelectedItem();
                if (selectedDoctor == null) {
                    JOptionPane.showMessageDialog(null, "请选择医生", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 获取选中医生的ID和姓名
                int doctorId = selectedDoctor.getId();
                String doctorName = selectedDoctor.getName();
                patDao.updatePatDoc(String.valueOf(patientId),doctorName);

                JOptionPane.showMessageDialog(null, "主治医生分配成功");
                dialog.dispose();
                refreshPatientTable(patientTableModel, role, currentUserName);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "分配失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());
        dialog.setVisible(true);
    }

    // 自定义下拉框渲染器
    private class DoctorListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Admin) {
                Admin doctor = (Admin) value;
                setText(doctor.getName()); // 只显示医生姓名
            }
            return this;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            HospitalManagementGUI gui = null;
            try {
                gui = new HospitalManagementGUI("张医生", "管理员");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            gui.setVisible(true);
        });
    }
}

@FunctionalInterface
interface StatValueProvider {
    String getValue() throws SQLException;
}